import { createStore } from 'vuex'

export default createStore({
    state: {
        user: null,
        token: localStorage.getItem('token') || null,
        permissions: []
    },
    mutations: {
        SET_AUTH(state, data){
            localStorage.setItem('user', JSON.stringify(state.user = data.user))
            localStorage.setItem('token', state.token = data.token)
            localStorage.setItem('perms',JSON.stringify(state.permissions = data.perms))
        },
        SET_USER(state, user) {
            localStorage.setItem('user', JSON.stringify(state.user = user))
        },
        SET_TOKEN(state, token) {
            state.token = token
            localStorage.setItem('token', token)
        },
        CLEAR_AUTH(state) {
            state.user = null
            state.token = null
            state.perms = []
            localStorage.removeItem('token')
            localStorage.removeItem('user')
            localStorage.removeItem('perms')
        },
    },
    actions: {

    },
    getters: {
        isAuthenticated: state => !!state.token,
        currentUser: state => {
            try{
                return state.user = (state.user||JSON.parse(localStorage.getItem('user')))
            }catch (e){
                return state.user || null
            }
        },
        permissions: state => {
            try{
                return state.permissions = (state.permissions||JSON.parse(localStorage.getItem('perms')))
            }catch (e){
                return state.permissions || []
            }
        },
        token: state => {
            try{
                return state.token = (state.token||localStorage.getItem('token'))
            }catch (e){
                return state.token || null
            }
        },
    }
})